import pymysql

def db_util(sql):
    """

    :param sql:
    :return:
    """
    conn = None
    cur = None
    try:
        conn = pymysql.connect(host="localhost", port=3306, user="root",password="zxc123!!", database="test_7_11", charset="utf8")
        cur = conn.cursor()
        cur.execute(sql)
        if sql.split()[0].lower() == "select":
            return cur.fetchall()
            # return "数据库查询的结果" + str(cur.fetchall())
        else:
            conn.commit()
            return "增删改操作成功，影响行数："+str(conn.affected_rows())

    except Exception as e:
        conn.rollback()
        return "数据库执行出错：" + str(e)

    finally:
        cur.close()
        conn.close()

if __name__ == '__main__':
    # result1 = db_util("select * from t_book")
    result1 = db_util("select title from t_book where id = 7")
    print(result1)
    print(result1[0])
    print(result1[0][0])
    print(result1[0][0][0])
    # result2 = db_util("insert into t_book(title, pub_date) values ('黑神话悟空','1986-01-01')")
    # print(result2)
    
